//
//  ImageHelpler.swift
//  covermedia
//
//  Created by travel on 2016/11/9.
//  Copyright © 2016年 covermedia. All rights reserved.
//

import UIKit
import Kingfisher
import KingfisherWebP

/// 图片相关的扩展函数，主要用于本模块（一般有第三方依赖）


// MARK: - 图片显示UIImageView相关扩展
public extension CMExt where DT == UIImageView {
    /// 设置图片
    ///
    /// - Parameters:
    ///   - url: 图片url地址
    ///   - placeholder: 缺省图片
    ///   - containSeparator: 是否包含 分隔符(;)，如果包含则图片地址为 url 解析后的首个地址，反之直接使用url
    public func setImage(with url: String?, placeholder: UIImage?, containSeparator:Bool = false) {
        guard  let image_url = url?.trimmingCharacters(in: .whitespaces) else {
            v.image = placeholder
            return
        }
        let target_url = containSeparator ? image_url.cm_Images().first : image_url
        if let u = target_url?.toURL{
//            v.kf.setImage(with: u, placeholder: placeholder, options: [.processor(WebPProcessor.default), .cacheSerializer(WebPSerializer.default)])
            v.kf.setImage(with: u, placeholder: placeholder, options: nil)

        } else {
            v.image = placeholder
        }
    }
}

// MARK: - 扩展 图片缓存
public extension ImageCache {
    
    /// web 缓存位置
    public class var cm_webCachePath: String {
        let path = (NSTemporaryDirectory() as NSString).appendingPathComponent("www")
        if !FileManager.default.fileExists(atPath: path) {
            _ = try? FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
        }
        return path
    }
    
    /// web缓存
    public static let cm_web = ImageCache.init(name: "wkwebview", path: ImageCache.cm_webCachePath)
}



// MARK: - 扩展字符串，用于图片下载
public extension CMExt where DT == String {
    /// 下载图片（如果本地有图片，则使用本地图片）
    ///
    /// - Parameter finish: 图片结束后处理函数(图片，错误，是否来自网络)
    public func retrieveImage(finish:((_: Image?, _: NSError?, _:Bool) -> ())? = nil) {
        let imageUrl = v
        // 检测本地是否已下载
        if let image = ImageCache.default.retrieveImageInDiskCache(forKey: imageUrl) {
            finish?(image, nil, false)
            return
        }
        
        // 下载图片
        guard let url = imageUrl.toURL else {
            finish?(nil, nil, false)
            return
        }
        ImageDownloader.default.downloadImage(with:url, options: nil, progressBlock: nil, completionHandler: { (image, error, imageURL, originalData) in
            finish?(image, error, true)
            guard let image = image, error == nil else {
                return
            }
            ImageCache.default.store(image, original: originalData, forKey: imageUrl, toDisk: true, completionHandler: nil)
        })
    }
    
    /// 下载图片(覆盖已有的图片)
    ///
    /// - Parameter finish: 图片结束后处理函数(图片，错误，是否来自网络)
    public func downloadImage(finish:((_: Image?, _: NSError?, _:Bool) -> ())? = nil) {
        let imageUrl = v
        guard let url = imageUrl.toURL else {
            finish?(nil, nil, false)
            return
        }
        ImageDownloader.default.downloadImage(with:url, options: nil, progressBlock: nil, completionHandler: { (image, error, imageURL, originalData) in
            finish?(image, error, true)
            guard let image = image, error == nil else {
                return
            }
            ImageCache.default.store(image, original: originalData, forKey: imageUrl, toDisk: true, completionHandler: nil)
        })
    }
}
